<template>
	<view class="">
		<NavBar title="订单提交" :isShowLeftBtn="false">
		</NavBar>
	</view>
	<view class="content" :style="{minHeight:contentHeight}">
		<view class="main">
			<view class="m_t_56 m_b_64" style="text-align: center;">
				<text class="f_32_0_b">
					订单提交
				</text>
			</view>
			<view class="form_box">
				<view class="form_item form_input">
					<up-input v-model="form.order_no" placeholder="请输入订单编号" border="none" fontSize="26rpx"></up-input>
				</view>
				<view class="form_item form_input">
					<up-input v-model="form.customer_name" placeholder="请输入客户名称" border="none"
						fontSize="26rpx"></up-input>
				</view>
				<view class="form_item form_order_detail m_b_22" v-for="(item,index) in form.goods" :key="index">
					<view class="m_b_32 flex_both">
						<text class="f_28_0_b">
							销售订单明细
						</text>
						<view class="m_b_4" @click="onDelGood(index)" v-if="index>0">
							<up-icon name="trash" color="#888888" size="18" :bold="true"></up-icon>
						</view>
					</view>
					<view class="flex_both m_b_22">
						<view class="form_order_detail_input">
							<up-input v-model="item.name" placeholder="请输入名称" border="none" fontSize="26rpx"></up-input>
						</view>
						<view class="form_order_detail_input">
							<up-input v-model="item.model" placeholder="请输入型号" border="none"
								fontSize="26rpx"></up-input>
						</view>
					</view>
					<view class="flex_both m_b_22">
						<view class="form_order_detail_input">
							<up-input type="digit" v-model="item.price" placeholder="请输入单价" border="none"
								fontSize="26rpx" @change="(e)=>{onGoodsPriceChange(e,index)}"></up-input>
						</view>
						<view class="form_order_detail_input">
							<up-input type="number" v-model="item.num" placeholder="请输入数量" border="none"
								fontSize="26rpx" @change="(e)=>{onGoodsNumChange(e,index)}"></up-input>
						</view>
					</view>
					<view class="flex_both m_b_22">
						<view class="upload_box">
							<up-upload :fileList="item.fileList" @afterRead="afterRead" @delete="deletePic"
								:name="index" multiple :maxCount="1" width="190rpx" height="190rpx">
								<view class="upload_box">
									<view class="">
										<up-icon name="/static/images/salesman/upload_icon.png" color="#4E4E4E"
											size="40"></up-icon>
									</view>
								</view>
							</up-upload>
						</view>
						<view class="desc_box">
							<up-textarea v-model="item.desc" placeholder="请输入所需采购明细主要技术参数，型 号（可附图）"
								border="none"></up-textarea>
						</view>
					</view>
					<view class="total_box flex_both m_b_32">
						<text class="f_26_0">
							总价
						</text>
						<text class="f_26_0" style="color: #F13C3C;">
							￥{{item.total}}
						</text>
					</view>
					<view class="add_box" @click="onAddGood(index)">
						<view class="add_icon m_r_12">
							<view class="m_b_4">
								<up-icon name="plus" color="#3665FF" size="8" :bold="true"></up-icon>
							</view>
						</view>
						<view class="m_b_4">
							<text class="f_26_f" style="color: #3665FF;">
								点击增加一行
							</text>
						</view>
					</view>

				</view>
				<view class="form_item form_input flex_both">
					<text class="f_26_0">
						总价
					</text>
					<text class="f_26_0" style="color: #F13C3C;">
						￥{{form.total}}
					</text>
				</view>
				<view class="form_item form_input">
					<up-input v-model="form.delivery_address" placeholder="请输入送货地址" border="none"
						fontSize="26rpx"></up-input>
				</view>
				<view class="form_item form_input">
					<up-input v-model="form.contact_name" placeholder="请输入联系人" border="none"
						fontSize="26rpx"></up-input>
				</view>
				<view class="form_item form_input ">
					<up-input v-model="form.contact_phone" type="number" placeholder="请输入联系电话" border="none"
						fontSize="26rpx"></up-input>
				</view>
				<view class="m_t_26 m_b_54">
					<view class="m_b_24">
						<text class="f_26_0_b">
							销售合同（订单）附图
						</text>
					</view>
					<view class="">
						<view class="">
							<up-upload :fileList="htImg.fileList" @afterRead="afterRead2" @delete="deletePic2" multiple
								:maxCount="6" width="190rpx" height="190rpx">
								<view class="upload_box">
									<view class="">
										<up-icon name="/static/images/salesman/upload_icon.png" color="#4E4E4E"
											size="40"></up-icon>
									</view>
								</view>
							</up-upload>
						</view>
					</view>
				</view>
				<view class="submit_btn">
					<up-button throttleTime="1000" @click="addOrder">
						<text class="f_28_f">
							立即提交
						</text>
					</up-button>
				</view>
			</view>
		</view>
	</view>
	<Tabbar :activeTab="0"></Tabbar>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import NavBar from "@/components/navbar.vue"
	import Tabbar from "@/components/tabbar.vue"
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	onLoad(() => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 76 + 100}rpx - env(safe-area-inset-bottom))`
			}
		});
	})


	const onAddGood = (e) => {
		form.value.goods.push({
			name: "",
			model: "",
			price: '',
			num: '',
			desc: "",
			images: "",
			fileList: [],
			total: 0
		})
	}
	const onDelGood = (e) => {
		form.value.goods.splice(e, 1)
		getAllPrice()
	}

	// 商品
	// 删除图片
	const deletePic = (event) => {
		let fileList = form.value.goods[`${event.name}`][`fileList`]
		fileList.splice(event.index, 1);
	};
	// 新增图片
	const afterRead = async (event) => {
		let fileList = form.value.goods[`${event.name}`][`fileList`]
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.length;
		lists.map((item) => {
			fileList.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			console.log(result);
			let item = fileList[fileListLen];
			fileList.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	// 销售合同
	// 删除图片
	const htImg = ref({
		fileList: []
	})
	const deletePic2 = (event) => {
		let fileList = htImg.value.fileList
		fileList.splice(event.index, 1);
	};
	// 新增图片
	const afterRead2 = async (event) => {
		let fileList = htImg.value.fileList
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.length;
		lists.map((item) => {
			fileList.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			console.log(result);
			let item = fileList[fileListLen];
			fileList.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: proxy.$config.baseUrl + '/api/common/upload',
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				success: (res) => {
					setTimeout(() => {
						resolve(JSON.parse(res.data).data.fullurl);
					}, 1000);
				},
			});
		});
	};

	const form = ref({
		order_no: "",
		customer_name: "",
		delivery_address: "",
		contact_name: "",
		contact_phone: "",
		order_files: "",
		total: 0,
		goods: [{
			name: "",
			model: "",
			price: '',
			num: '',
			desc: "",
			images: "",
			fileList: [],
			total: 0
		}]
	})

	const formRules1 = ref({
		order_no: "请输入订单号",
		customer_name: "请输入客户名称",
		delivery_address: "请输入送货地址",
		contact_name: "请输入联系人",
		contact_phone: "请输入联系电话",
		order_files: "请上传销售合同",

	})
	const goodsRule = ref({
		name: "名称",
		model: "型号",
		price: '单价',
		num: '数量',
		desc: "技术参数",
	})
	const addOrder = async () => {
		let params = JSON.parse(JSON.stringify(form.value))
		console.log(params);
		// 处理参数
		delete params.total
		params.goods.forEach(v => {
			delete v.total
			if (v.fileList.length > 0) {
				v.fileList.forEach((v, index) => {
					if (index == 0) {
						v.images += v.url
					} else {
						v.images += ',' + v.url
					}
				})
			}
			delete v.fileList
		})
		if (htImg.value.fileList.length > 0) {
			htImg.value.fileList.forEach((v, index) => {
				if (index == 0) {
					params.order_files += v.url
				} else {
					params.order_files += ',' + v.url
				}
			})
		}
		// 验证参数
		let flag = false
		for (let key in formRules1.value) {
			if (!params[key]) {
				uni.$u.toast(formRules1.value[key])
				flag = true
				break;
			}
		}
		if (flag) {
			return
		}
		params.goods.forEach((v, index) => {
			for (let key in goodsRule.value) {
				if (!v[key]) {
					uni.$u.toast('订单' + (index + 1) + goodsRule.value[key] + '为空')
					flag = true
					break;
				}
			}
		})

		if (flag) {
			return
		}
	
		uni.request({
			url: proxy.$config.baseUrl + '/api/Salesman/houseContract',
			data: params,
			method: "POST",
			header: {
				'content-type': "application/json",
				token: uni.getStorageSync('token')
			},
			success: function (res) {
				if (res.data.code == 1) {
					uni.showToast({
						title: "提交成功",
						icon: 'success'
					})
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/salesman/order"
						})
					}, 800)
				} else {
					uni.$u.toast(res.data.msg)
				}
			},
			fail: function (err) {
				console.error(err);
			},
			complete() {

			}
		});

		let res = await proxy.$http('', { ...params })
	}
	// 计算总价
	const onGoodsPriceChange = (e, index) => {
		let gArr = form.value.goods
		if (!e) {
			gArr[index].total = 0
		}
		if (e && gArr[index].num) {
			gArr[index].total = parseFloat(e) * parseInt(gArr[index].num)
		}
		getAllPrice()
	}
	const onGoodsNumChange = (e, index) => {
		let gArr = form.value.goods
		if (!e) {
			gArr[index].total = 0
		}
		if (e && gArr[index].price) {
			gArr[index].total = parseInt(e) * parseFloat(gArr[index].price)
		}
		getAllPrice()
	}
	const getAllPrice = () => {
		// 计算全部价格
		let count = 0
		form.value.goods.forEach(v => {
			count += v.total
		})
		form.value.total = count
	}
</script>
<style lang="scss" scoped>
	.content {
		background: #F2F2F2;
		padding: 20rpx;
		padding-bottom: 64rpx;

		.main {
			.form_box {
				.form_input {
					width: 668rpx;
					height: 92rpx;
					padding: 0 22rpx;
					background: #FFFFFF;
					box-shadow: 2rpx 6rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
					border-radius: 10rpx;
					border: 1px solid #EDEDEE;
					display: flex;
					align-items: center;
					margin-bottom: 26rpx;
				}

				.form_order_detail {
					padding: 30rpx 22rpx 40rpx 22rpx;
					background: #FFFFFF;
					box-shadow: 2rpx 6rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
					border-radius: 10rpx;
					border: 1px solid #EDEDEE;

					.form_order_detail_input {
						width: 282rpx;
						height: 66rpx;
						padding: 0 20rpx;
						background: #FFFFFF;
						border-radius: 10rpx;
						border: 1px solid #E4E4E5;
						display: flex;
						align-items: center;
					}



					.desc_box {
						width: 450rpx;
						height: 175rpx;
						background: #FFFFFF;
						border-radius: 10rpx;
						border: 1px solid #E4E4E5;
					}

					.total_box {
						width: 626rpx;
						height: 66rpx;
						padding: 0 20rpx;
						background: #FFFFFF;
						border-radius: 10rpx;
						border: 1px solid #E4E4E5;
					}

					.add_box {
						width: 665rpx;
						height: 65rpx;
						background: #F2F2F2;
						border: 1px solid #E4E4E5;
						display: flex;
						align-items: center;
						justify-content: center;

						.add_icon {
							width: 22rpx;
							height: 22rpx;
							background: #FFFFFF;
							border: 1px solid #88A3FB;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}
	}

	.upload_box {
		width: 192rpx;
		height: 175rpx;
		background: #FFFFFF;
		border-radius: 10rpx;
		border: 1px solid #E4E4E5;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	::v-deep.u-textarea__field {
		font-size: 26rpx !important;
	}
</style>